!function($) {

	var Modal = function() {
		var that = this;

		// 变量
		this.toggle = null;
		this.currentOpts = {};
		this.imgPreloader = new Image();

		$(document)
				.ready(
						function() {
							// 创建元素
							that.$modal = $('<div class="modal hide"></div>');
							that.$modal_close = $('<button title="Close(ESC)" type="button" class="modal-close">×</button>');
							that.$modal_content = $('<div class="modal-content"></div>');
							that.$modal_footer = $('<div class="modal-footer">Title</div>');

							that.$backdrop = $('<div class="modal-backdrop hide" />');
							that.$modal_tmp = $('<div class="modal-tmp"></div>');

							that.$modal.append(that.$modal_close);
							that.$modal.append(that.$modal_content);
							that.$modal.append(that.$modal_footer);
							that.$modal.appendTo(document.body);

							that.$backdrop.appendTo(document.body);
							that.$modal_tmp.appendTo(document.body);

							that.$modal_close.click($.modal.close);
						});
	}
	Modal.prototype = {
		constructor : Modal,
		_start : function() {
			var that = this;
			var toggle = this.toggle;
			var currentOpts = this.currentOpts = $(toggle).data('modalOptions');

			// 开始回调
			currentOpts.onStart(toggle, currentOpts);

			// 标题
			var title = currentOpts.title
					|| (toggle.nodeName ? $(toggle).attr('title')
							: toggle.title) || '';
			currentOpts.title = title;

			// 链接
			var href = currentOpts.href
					|| (toggle.nodeName ? $(toggle).attr('href') : toggle.href)
					|| null;
			if ((/^(?:javascript)/i).test(href) || href == '#') {
				href = null;
			}
			currentOpts.href = href;

			// 尺寸
			if (currentOpts.autoDimensions) {
				if (currentOpts.type == 'html' || currentOpts.type == 'inline'
						|| currentOpts.type == 'ajax') {
					currentOpts.width = 'auto';
					currentOpts.height = 'auto';
				} else {
					currentOpts.autoDimensions = false;
				}
			}

			// 类型
			if (!currentOpts.type) {
				this._error();
				return;
			}

			switch (currentOpts.type) {
			case 'html':
				this.$modal_tmp.html(currentOpts.content);
				this._process_inline();
				break;

			case 'inline':
				break;

			case 'image':
				this.imgPreloader = new Image();

				this.imgPreloader.onerror = function() {
					this._error();
				};

				this.imgPreloader.onload = function() {
					this.onerror = this.onload = null;
					that._process_image();
				};

				this.imgPreloader.src = href;
				break;

			case 'swf':
				break;

			case 'ajax':

				break;

			case 'iframe':
				break;
			}
		},
		_process_inline : function() {
			var currentOpts = this.currentOpts;

			var w = currentOpts.width, h = currentOpts.height;
			w = w == 'auto' ? 'auto' : w + 'px';
			h = h == 'auto' ? 'auto' : h + 'px';

			this.$modal_tmp.wrapInner('<div style="padding:20px 30px;"></div>');

			currentOpts.width = this.$modal_tmp.width();
			currentOpts.height = this.$modal_tmp.height();

			this._show();
		},
		_process_image : function() {
			var currentOpts = this.currentOpts;

			currentOpts.width = this.imgPreloader.width;
			currentOpts.height = this.imgPreloader.height;

			$("<img />").attr({
				'src' : this.imgPreloader.src,
				'alt' : this.imgPreloader.title
			}).appendTo(this.$modal_tmp);

			this._show();
		},
		_show : function() {
			var final_pos = this._get_zoom_to();

			this.$modal_content.css({
				'width' : final_pos.width,
				'height' : final_pos.height
			}).html(this.$modal_tmp.contents());

			this.$modal.css(final_pos);

			this.$modal.show();
			this.$backdrop.show();

			$(window).on('resize', $.proxy(this._resize, this));
			this._escape();
		},
		_get_zoom_to : function() {
			var currentOpts = this.currentOpts;

			var view = [ $(window).width(), $(window).height(),
					$(document).scrollLeft(), $(document).scrollTop() ];
			var to = {}
			var resize = currentOpts.autoScale;

			to.width = currentOpts.width;
			to.height = currentOpts.height;

			to.top = parseInt(Math.max(view[3] - 20, view[3]
					+ ((view[1] - to.height - 40) * 0.5)), 10);
			to.left = parseInt(Math.max(view[2] - 20, view[2]
					+ ((view[0] - to.width - 40) * 0.5)), 10);

			return to;
		},
		_error : function() {
			var that = this;

			if (false === that.currentOpts.onError(that.toggle,
					that.currentOpts)) {
				return;
			}

			that.currentOpts.titleShow = false;

			that.currentOpts.width = 'auto';
			that.currentOpts.height = 'auto';

			that.$modal_tmp
					.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');

			that._process_inline();
		},
		_resize : function() {
			var $window = $(window);

			var windowWidth = $window.width();
			var windowHeight = $window.height();
			var modalWidth = this.$modal.outerWidth();
			var modalHeight = this.$modal.outerHeight();

			var top = (windowHeight - modalHeight) / 2;
			var left = (windowWidth - modalWidth) / 2;

			this.$modal.css({
				position : 'absolute',
				top : (top > 0 ? top : 0) + 'px',
				left : (left > 0 ? left : 0) + 'px'
			});
		},
		_escape : function() {
			var that = this;
			$(document).on('keyup.dismiss.modal', function(e) {
				if (e.keyCode === 27) {
					that.close();
				}
			});
		},
		close : function() {
			alert("close");
		}
	}

	// 创建一个实例
	$.modal = new Modal();
	// ------------------------------------------------------
	$.fn.modal = function(options) {
		if (!$(this).length) {
			return this;
		}

		var $this = (this);

		if (!options) {
			options = {};
		}

		var modalOptions = $this.data('modalOptions');

		if (!modalOptions) {
			$this.data('modalOptions', $.extend({}, $.fn.modal.defaults,
					options));
		}

		$this.on('click.show.modal', function(e) {
			e.preventDefault();
			$.modal.toggle = this;
			$.modal._start();

			return false;
		});

		return this;
	}

	$.fn.modal.defaults = {
		width : 160,
		height : 140,
		autoScale : true,
		autoDimensions : true,

		hideOnOverlayClick : true,
		hideOnContentClick : false,

		overlayShow : true,
		overlayOpacity : 0.7,
		overlayColor : '#777',

		titleShow : true,

		showCloseButton : true,
		enableEscapeButton : true,

		type : "image",
		href : "img/34.jpg",
		title : "title",
		content : '<div id="inline1" style="width:400px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam quis mi eu elit tempor facilisis id et neque. Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare. Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum, vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in. Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc aliquet tempus sem, id aliquam diam varius ac. Maecenas nisl nunc, molestie vitae eleifend vel, iaculis sed magna. Aenean tempus lacus vitae orci posuere porttitor eget non felis. Donec lectus elit, aliquam nec eleifend sit amet, vestibulum sed nunc.</div>',

		onStart : function() {
		},
		onCancel : function() {
		},
		onComplete : function() {
		},
		onCleanup : function() {
		},
		onClosed : function() {
		},
		onError : function() {
		}
	};

}(window.jQuery);
